<template>
  <div class="app-container">
    <div class="header" style="display: flex; justify-content: space-between">
      <el-button @click="$router.push('/main/xingzheng/gudingzichan')"
        >返回</el-button
      >
      <span>
        <el-button
          type="primary"
          @click="$router.push('/main/xingzheng/sblvlibiao/sblvlibiaoList')"
          >列表</el-button
        >

        <!-- <div style=""> -->
        <el-button v-if="!isViewMode" type="primary" @click="submitForm"
          >保存</el-button
        >
        <!-- </div> -->

        <el-button type="info" icon="el-icon-printer" @click="printForm"
          >打印</el-button
        >
      </span>
    </div>

    <h2>机器设备履历卡</h2>
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <div
        style="
          display: flex;
          justify-content: space-evenly;
          align-items: center;
          margin-bottom: 10px;
        "
      >
        <el-form-item label="编号/卡号" prop="cardNumber">
          <el-input v-model="formData.cardNumber" :disabled="isViewMode" />
        </el-form-item>
        <el-form-item label="建卡人" prop="cardCreator">
          <el-input v-model="formData.cardCreator" :disabled="isViewMode" />
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="formData.createDate"
            type="date"
            placeholder="选择日期"
            :disabled="isViewMode"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </div>

      <table border="1" style="width: 100%; text-align: center">
        <tr>
          <td>机器名称</td>
          <td>
            <el-input v-model="formData.machineName" :disabled="isViewMode" />
          </td>
          <td>规格型号</td>
          <td>
            <el-input
              v-model="formData.specificationModel"
              :disabled="isViewMode"
            />
          </td>
          <td>机器序号</td>
          <td>
            <el-input
              v-model="formData.machineSerialNumber"
              :disabled="isViewMode"
            />
          </td>
        </tr>
        <tr>
          <td>购入日期</td>
          <td>
            <el-date-picker
              v-model="formData.purchaseDate"
              type="date"
              placeholder="选择日期"
              :disabled="isViewMode"
              value-format="yyyy-MM-dd"
            />
          </td>
          <td>保固期限</td>
          <td>
            <el-input
              v-model="formData.warrantyPeriod"
              :disabled="isViewMode"
            />
          </td>
          <td>报废日期</td>
          <td>
            <el-date-picker
              v-model="formData.scrapDate"
              type="date"
              placeholder="选择日期"
              :disabled="isViewMode"
              value-format="yyyy-MM-dd"
            />
          </td>
        </tr>
      </table>

      <h3>制造商联络栏</h3>
      <table border="1" style="width: 100%; text-align: center">
        <tr>
          <td>厂商名称</td>
          <td>
            <el-input
              v-model="formData.manufacturerName"
              :disabled="isViewMode"
            />
          </td>
          <td>电话</td>
          <td>
            <el-input
              v-model="formData.manufacturerPhone"
              :disabled="isViewMode"
            />
          </td>
          <td>传真</td>
          <td>
            <el-input
              v-model="formData.manufacturerFax"
              :disabled="isViewMode"
            />
          </td>
        </tr>
        <tr>
          <td>地址</td>
          <td colspan="5">
            <el-input
              v-model="formData.manufacturerAddress"
              :disabled="isViewMode"
            />
          </td>
        </tr>
        <tr>
          <td>备注</td>
          <td colspan="5">
            <el-input
              v-model="formData.manufacturerRemark"
              type="textarea"
              :disabled="isViewMode"
            />
          </td>
        </tr>
      </table>

      <h3>代理商联络栏</h3>
      <table border="1" style="width: 100%; text-align: center">
        <tr>
          <td>厂商名称</td>
          <td>
            <el-input v-model="formData.agentName" :disabled="isViewMode" />
          </td>
          <td>电话</td>
          <td>
            <el-input v-model="formData.agentPhone" :disabled="isViewMode" />
          </td>
          <td>传真</td>
          <td>
            <el-input v-model="formData.agentFax" :disabled="isViewMode" />
          </td>
        </tr>
        <tr>
          <td>地址</td>
          <td colspan="5">
            <el-input v-model="formData.agentAddress" :disabled="isViewMode" />
          </td>
        </tr>
        <tr>
          <td>购入价格</td>
          <td>
            <el-input-number
              v-model="formData.purchasePrice"
              :disabled="isViewMode"
              :precision="2"
              :step="0.01"
            />
          </td>
          <td>备注</td>
          <td colspan="4">
            <el-input
              v-model="formData.agentRemark"
              type="textarea"
              :disabled="isViewMode"
            />
          </td>
        </tr>
      </table>

      <h3>维护（保养）记录</h3>
      <div class="table-container" style="margin-bottom: 10px">
        <el-button
          type="primary"
          @click="addMaintenanceRecord"
          :disabled="isViewMode"
          >新增</el-button
        >
        <el-button
          type="danger"
          @click="deleteSelectedRecords"
          :disabled="isViewMode || !hasSelectedRecords"
          >删除选中</el-button
        >
      </div>

      <el-table
        :data="maintenanceRecords"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="() => !isViewMode"
        />
        <el-table-column label="日期" width="180">
          <template slot-scope="scope">
            <el-date-picker
              v-model="scope.row.maintenanceDate"
              type="date"
              placeholder="选择日期"
              :disabled="isViewMode"
              value-format="yyyy-MM-dd"
            />
          </template>
        </el-table-column>
        <el-table-column label="维修（保养）原因">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.maintenanceReason"
              :disabled="isViewMode"
            />
          </template>
        </el-table-column>
        <el-table-column label="零件更换记录">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.partReplacement"
              :disabled="isViewMode"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额" width="150">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.amount"
              :disabled="isViewMode"
              :precision="2"
              :step="0.01"
            />
          </template>
        </el-table-column>
        <el-table-column label="维修人员">
          <template slot-scope="scope">
            <el-input v-model="scope.row.repairPerson" :disabled="isViewMode" />
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :disabled="isViewMode" />
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
import {
  saveWithMaintenance,
  getMaintenanceList,
  getMachineDetail,
} from "@/api/machine";

export default {
  name: "Sblvlibiao",
  data() {
    return {
      formData: {
        id: null,
        cardNumber: "",
        cardCreator: "",
        createDate: null,
        machineName: "",
        specificationModel: "",
        machineSerialNumber: "",
        purchaseDate: null,
        warrantyPeriod: "",
        scrapDate: null,
        manufacturerName: "",
        manufacturerPhone: "",
        manufacturerFax: "",
        manufacturerAddress: "",
        manufacturerRemark: "",
        agentName: "",
        agentPhone: "",
        agentFax: "",
        agentAddress: "",
        purchasePrice: null,
        agentRemark: "",
      },
      maintenanceRecords: [],
      selectedRecords: [],
      rules: {
        cardNumber: [
          { required: true, message: "请输入编号/卡号", trigger: "blur" },
        ],
        cardCreator: [
          { required: true, message: "请输入建卡人", trigger: "blur" },
        ],
        machineName: [
          { required: true, message: "请输入机器名称", trigger: "blur" },
        ],
      },
      isAllChecked: false,
      pageType: "add", // 页面类型：add, edit, view
    };
  },
  computed: {
    hasSelectedRecords() {
      return this.selectedRecords.length > 0;
    },
    isViewMode() {
      return this.pageType === "view";
    },
    pageTitle() {
      const titles = {
        add: "新增机器设备",
        edit: "编辑机器设备",
        view: "查看机器设备详情",
      };
      return titles[this.pageType] || "机器设备";
    },
  },
  created() {
    this.initPageData();
  },
  methods: {
    async initPageData() {
      // 从路由参数获取信息
      const { id, type } = this.$route.query;
      this.pageType = type || "add";

      if (id) {
        try {
          // 获取机器设备详情
          const response = await getMachineDetail(id);
          if (response && response.data) {
            this.formData = { ...response.data };
            // 获取维护记录
            await this.loadMaintenanceRecords();
          } else {
            this.$message.error("未找到相关数据");
            this.$router.push("/main/xingzheng/sblvlibiao/sblvlibiaoList");
          }
        } catch (error) {
          console.error("获取数据失败:", error);
          this.$message.error("获取数据失败");
          this.$router.push("/main/xingzheng/sblvlibiao/sblvlibiaoList");
        }
      }
    },
    async loadMaintenanceRecords() {
      if (this.formData.id) {
        try {
          const response = await getMaintenanceList(this.formData.id);
          this.maintenanceRecords = response.data || [];
        } catch (error) {
          console.error("获取维护记录失败:", error);
          this.$message.error("获取维护记录失败");
        }
      }
    },
    addMaintenanceRecord() {
      this.maintenanceRecords.push({
        id: null, // 新增时id为null
        machineId: this.formData.id || null, // 如果formData.id不存在，设为null
        maintenanceDate: null,
        maintenanceReason: "",
        partReplacement: "",
        amount: 0,
        repairPerson: "",
        remark: "",
      });
    },
    handleSelectionChange(val) {
      this.selectedRecords = val;
    },
    deleteSelectedRecords() {
      this.$confirm("确认删除选中的记录?", "提示", {
        type: "warning",
      }).then(() => {
        this.maintenanceRecords = this.maintenanceRecords.filter(
          (record) => !this.selectedRecords.includes(record)
        );
        this.selectedRecords = [];
      });
    },
    toggleAllCheck() {
      this.maintenanceRecords.forEach((record) => {
        record.isChecked = this.isAllChecked;
      });
    },
    updateAllCheckedStatus() {
      this.isAllChecked = this.maintenanceRecords.every(
        (record) => record.isChecked
      );
    },
    async submitForm() {
      try {
        await this.$refs.form.validate();

        // 准备要保存的数据
        const saveData = {
          machineEquipment: this.formData,
          maintenanceRecords: this.maintenanceRecords,
        };

        // 保存所有数据
        const result = await saveWithMaintenance(saveData);

        if (result) {
          this.$message.success("保存成功");
          // 保存成功后返回列表页
          this.$router.push("/main/xingzheng/sblvlibiao/sblvlibiaoList");
        }
      } catch (error) {
        console.error("保存失败:", error);
        this.$message.error("保存失败：" + (error.message || "未知错误"));
      }
    },
    printForm() {
      window.print();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  width: 210mm;
  margin: 0 auto;
  background-color: #fff;
  padding: 20px;
  min-height: calc(100vh - 40px);
}
.el-form {
  //   padding: 20px;
}

table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 20px;
}

th,
td {
  border: 1px solid #dcdfe6;
  padding: 12px 8px;
}

.el-input,
.el-input-number {
  width: 100%;
}

h3 {
  margin: 20px 0;
  padding-left: 10px;
  border-left: 4px solid #409eff;
  font-size: 16px;
}

.el-table {
  margin-bottom: 20px;
}
@media print {
  .header,
  .table-container {
    display: none !important;
  }
}
</style>